package com.syq.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.syq.exception.HospitalException;
import com.syq.mapper.SysUserMapper;
import com.syq.pojo.SysRole;
import com.syq.pojo.SysUser;
import com.syq.service.SysUserService;
import enums.HospitalExceptionEnums;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @ClassName: HospitalRealm
 * @Description: TODO
 * @Create by: syq
 * @Date: 2022/7/18 19:47
 */


public class HospitalRealm extends AuthorizingRealm {


    @Autowired
    private SysUserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String loginName = (String) token.getPrincipal();

        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("login_name",loginName);

        SysUser sysUser = userMapper.selectOne(queryWrapper);

        if (sysUser==null){
            throw  new HospitalException(HospitalExceptionEnums.USERNAME_PASSWORD_ERROR);
        }

        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(sysUser,sysUser.getPwd(),this.getName());

        info.setCredentialsSalt(ByteSource.Util.bytes(sysUser.getSalt()));

        return info;
    }
}
